<template>
  <!-- 单独的部门组件 -->
  <div id="deptlist">
    <vxe-toolbar perfect>
      <template #buttons>
        <div class="smallToolTitle">科室信息</div>
        <vxe-input style="width: 130px" v-model="deptForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findDeptList" @keyup="keyupEnter" @search-click="handleSearch(deptForm.searchValue)"></vxe-input>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findDeptList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addDept(propOrgId, '', '')"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveDept"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="showDataLoading" @click="pullDept"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="deptTable" border="inner" height="auto" class="mytable-scrollbar" :loading="showLoading" :data="departList" :expand-config="{ expandAll: true, reserve: true }" @current-change="deptRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
          isArrow: true,
          isTab: true,
          isEdit: true
        }" :tree-config="{
          expandAll: true,
          transform: true,
          rowField: 'id',
          parentField: 'parentId'
        }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
        <!-- tree-node 只对 tree-config 配置时有效，指定为树节点 -->
        <!-- v-if="row.code.toLowerCase() !== 'all'" -->
        <vxe-column field="code" title="编码" width="140" tree-node :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input type="text" :underline="false" v-model="row.code"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="name" title="名称" width="120" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input type="text" :underline="false" v-model="row.name"></vxe-input>
          </template>
        </vxe-column>

        <vxe-column field="contactTel" title="联系电话" width="120" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input type="text" :underline="false" v-model="row.contactTel"></vxe-input>
          </template>
        </vxe-column>

        <vxe-column field="address" title="地址" min-width="110" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input type="text" :underline="false" v-model="row.address"></vxe-input>
          </template>
        </vxe-column>

        <vxe-column title="操作" width="90" align="center" fixed="right">
          <template #default="{ row }">
            <!-- v-if="row.code.toLowerCase() !== 'all'" -->
            <div>
              <el-tooltip class="item" effect="dark" content="新建子分组" placement="right">
                <vxe-button type="text" status="primary" icon="vxe-icon-square-plus" circle @click.native="addDept(propOrgId, row.id, row)"></vxe-button>
              </el-tooltip>
              <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteDept(row)"></vxe-button>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// 全局变量定义区 ==========
//暴露属性和方法
defineExpose({
  initPage
});

let propOrgId = ''; //接收传过来的机构id
let showLoading = ref(false); //刷新加载状态
let saveLoading = ref(false); //保存加载状态
let showDataLoading = ref(false);

// 部门根据关键字查询
let deptForm = {
  id: '',
  parentId: null,
  parentName: '',
  orgId: null,
  orgName: '',
  code: '',
  name: '',
  address: '',
  isDeactivated: true,
  contactTel: '',
  internalContactNumber: '',
  //用户输入查询内容
  searchValue: ''
};

let deptTable = ref(); //部门表格ref
let departList: any = reactive([]); //部门列表数据

// 方法定义区 =============
function initPage(row: any, dept?: any) {
  //   console.log('父组件机构给部门子组件传过来的值', row);
  deptForm.id = row.id;
  deptForm.orgName = row.name;
  propOrgId = row.id;
  findDeptList(); //获取部门列表信息
}

// 点击部门当前行触发的事件
function deptRowClick({ row }: any) {
  proxy.$emit('getCurrentOrgDept', row);
  (proxy.$refs.deptTable as any).setCurrentRow(row);
}

// 获取部门列表
function findDeptList() {
  showLoading.value = true;
  departList.length = 0;
  const $table = deptTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
  }
  const orgId = propOrgId;

  proxy.$emit('getRefresh', deptForm);

  const url = '/api/sys/findDepartmentList';
  proxy.$http
    .get(url, { params: { orgId: propOrgId } })
    .then((res: any) => {
      departList.push(...res.data.deptList);
      // if(proxy.isChildren){
      // deptRowClick({row: departList[0]})//默认选中第一个
      // }
      const $table = deptTable.value;
      // $table.loadData(departList);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取部门异常',VxeNotifyType.error)
    });
}

//搜索部门
function handleSearch(row: any) {
  departList.length = 0;

  const $table = deptTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const orgId = propOrgId;
  const url = '/api/sys/findDepartmentList';
  proxy.$http
    .get(url, { params: { keywords: row, orgId: propOrgId } })
    .then((res: any) => {
      departList.push(...res.data.deptList);
      // if(proxy.isChildren){
      // orgRowClick({row: this.orgaList[0]})
      // }
      const $table = deptTable.value;
      // $table.loadData(departList);
    })
    .catch((err: any) => {
      VxeMessage('搜索刷新部门失败', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(deptForm.searchValue);
  }
}

// 清空搜索条件
function clearForm() {
  deptForm = {
    id: '',
    parentId: null,
    parentName: '',
    orgId: null,
    orgName: '',
    code: '',
    name: '',
    address: '',
    isDeactivated: true,
    contactTel: '',
    internalContactNumber: '',
    //用户输入查询内容
    searchValue: ''
  };
}

// 同步数据
function pullDept() {
  showDataLoading.value = true;
  const url = '/api/sys/syncOrgDepartments';
  const params = {
    url: (window as any).apiUrl.VUE_APP_INTERFACE_URL+ '/lisInterface/lisInterfacePost',
    code: 'GET_DEPARTMENT'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      showDataLoading.value = false;
      findDeptList();
    })
    .catch((err: any) => {
      showDataLoading.value = false;
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

// 新建一级/子部门
async function addDept(orgids: any, parentids: any, row: any) {
  // clearForm();
  const $table = deptTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      code: '',
      name: '',
      contactTel: '',
      address: '',
      orgId: orgids != '' || orgids != null ? orgids : null, //左侧机构传过来的id
      parentId: parentids != '' || parentids != null ? parentids : null, //自己是否有id
      id: ''
    };
    //departList.push(record);
    $table.loadData(departList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }
  }
}

// 保存
async function saveDept() {
  saveLoading.value = true;
  const $table = deptTable.value;
  if ($table) {
    const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    // 修改部门
    updateRecords.forEach((e: any) => {
      const url = '/api/sys/editDepartment';
      const tOrganization = e;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          // findDeptList();
          if (res.status.code === 1) {
            VxeMessage('修改部门成功', VxeNotifyType.success);
          } else {
            VxeMessage('修改部门失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改部门异常', VxeNotifyType.error);
        });
    });

    // 新增部门
    InsertRecords.forEach((ele: any) => {
      const url = '/api/sys/addDepartment';
      const tOrganization = ele;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('新增部门成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增部门失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增部门异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findDeptList();
      saveLoading.value = false;
    }, 500);
  }
}

// 删除部门
function deleteDept(row: any) {
  const $table = deptTable.value;
  $table.setAllTreeExpand(true);
  proxy
    .$confirm('确定删除此部门？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/deleteDepartment/' + row.id;
      if (row.id) {
        proxy.$http.delete(url).then((res: any) => {
          if (res.status.code != 1) {
            VxeMessage('删除部门失败', VxeNotifyType.error);
          } else {
            VxeMessage('删除部门成功', VxeNotifyType.success);
          }
          findDeptList();
        });
      } else {
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除部门成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}
</script>

<style lang="scss" scoped>
#deptlist {
  height: 100%;
  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }
  .tableBox {
    height: calc(100% - 39px);
  }
}
</style>
